﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Angerona.Model;
using Microsoft.Phone.Scheduler;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;


namespace Angerona
{
    public partial class VehicleDetail : PhoneApplicationPage
    {
        private int idOfCar = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string);

        private VehiclesTable Vehicle;
        private bool dp_fuel_changed = false;
        private bool dp_mantinace_changed = false;
        private bool dp_general_changed = false;
        DateTime defaultDate = new DateTime(2013, 1, 1);
        public VehicleDetail()
        {
            InitializeComponent();
            RefreshAllData();
            this.DataContext = App.ViewModel;
            
        }

        public void RefreshAllData()
        {
            App.ViewModel.LoadCollectionsFromDatabase();
            ReadData();
            ReadFuelData();
            ReadGenericData();
            ReadMaintenanceData();
        }

        private void ReadData()
        {
            //carname.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carmanufacter.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carmodel.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carfuel.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carhorse.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carkw.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carvolume.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carplate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carserial.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carboughtdate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carproductiondate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            carinitialkm.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            cartraveledkm.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancecompany.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancenumber.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            assurancedate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            bollodate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            revisiondate.Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"];
            if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoCliccked"))
            {
                
                int ID = Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string);
                Vehicle = App.ViewModel.getElementWithID(ID);
                if (Vehicle.ImageOfCar != null)
                {
                    BitmapImage bi = new BitmapImage();
                    using (IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        using (IsolatedStorageFileStream imageFileStream = myIsoStore.OpenFile(Vehicle.ImageOfCar, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                        {
                            bi.SetSource(imageFileStream);
                        }
                        imageOfTheCar.Source = bi;
                    }
                    imageOfTheCar.Visibility = Visibility.Visible;
                }
                carname.Text = Vehicle.VehicleName;
                carmanufacter.Text = Vehicle.Manufacter;
                carmodel.Text = Vehicle.VehicleModel;
                carfuel.Text = Vehicle.FuelType;
                carhorse.Text = Vehicle.HorsePower;
                carkw.Text = Vehicle.KwPower;
                carvolume.Text = Vehicle.EngineCapacity;
                carplate.Text = Vehicle.PlateNumber;
                carserial.Text = Vehicle.SerialNumber;
                carboughtdate.Text = String.Format(Vehicle.PurchasedDate.ToString("d"));
                carproductiondate.Text = String.Format(Vehicle.ProductionDate.ToString("d"));
                carinitialkm.Text = Vehicle.PurchasedKm;
                cartraveledkm.Text = Vehicle.TraveledKm;
                assurancecompany.Text = Vehicle.AssuranceCompany;
                assurancenumber.Text = Vehicle.AssuranceNumber;
                assurancedate.Text = String.Format(Vehicle.AssuranceDate.ToString("d"));
                bollodate.Text = String.Format(Vehicle.Bollo.ToString("d"));
                revisiondate.Text = String.Format(Vehicle.Revision.ToString("d"));


                FuelList.ItemsSource = Vehicle.Refueling;
                MaintenanceList.ItemsSource = Vehicle.MaintenanceEntitySet;
                GenericList.ItemsSource = Vehicle.GenericEntitySet;
            }
        }

        private void ReadFuelData()
        {
            if (!dp_fuel_changed)
            {
                allQuantityMade.Text = App.ViewModel.sumOfAllQuantityFuel(Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string)).ToString();
                allFuelOperationsCost.Text = App.ViewModel.sumOfAllSpentFuelDataOfCar(Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string)).ToString();
            }
            else
            {
                DateTime fromDate = (DateTime)dp_fuel_from_date.Value;
                DateTime toDate = (DateTime)dp_fuel_to_date.Value;
                fromDate = CheckAgeOrDefault(fromDate);
                toDate = CheckAgeOrDefault(toDate);

                allFuelOperationsCost.Text = (App.ViewModel.SpentFuelDataOfCarBetweenDate(idOfCar, fromDate, toDate)).ToString();
                allQuantityMade.Text = (App.ViewModel.sumQuantityFuelBetweenDate(idOfCar, fromDate, toDate)).ToString();

                FuelList.ItemsSource = App.ViewModel.getFuelBetweenDate(idOfCar, fromDate, toDate);
            }
        }

        private void ReadMaintenanceData()
        {

            if (!dp_mantinace_changed)
                allMaintenanceSpentLabel.Text = App.ViewModel.sumOfAllMaintenanceCost(Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string)).ToString();
            else
            {
                DateTime fromDate = (DateTime)dp_man_from_date.Value;
                DateTime toDate = (DateTime)dp_man_to_date.Value;
                fromDate = CheckAgeOrDefault(fromDate);
                toDate = CheckAgeOrDefault(toDate);

                allMaintenanceSpentLabel.Text = (App.ViewModel.sumQuantityMantinanceBetweenDate(idOfCar, fromDate, toDate)).ToString();

                MaintenanceList.ItemsSource = App.ViewModel.getMantinanceBetweenDate(idOfCar, fromDate, toDate);
            }
        }

        private void ReadGenericData()
        {
            if (!dp_general_changed)
                allGenericSpentLabel.Text = App.ViewModel.sumOfAllGenericCost(Convert.ToInt32(IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string)).ToString();
            else
            {
                DateTime fromDate = (DateTime)dp_gen_from_date.Value;
                DateTime toDate = (DateTime)dp_gen_to_date.Value;
                fromDate = CheckAgeOrDefault(fromDate);
                toDate = CheckAgeOrDefault(toDate);

                allGenericSpentLabel.Text = (App.ViewModel.sumQuantityGenericBetweenDate(idOfCar,fromDate,toDate)).ToString();

                GenericList.ItemsSource = App.ViewModel.getGenericBetweenDate(idOfCar, fromDate, toDate);
            }
        }

        private void Vpivot_selChanged(object sender, SelectionChangedEventArgs e)
        {
            switch ((sender as Pivot).SelectedIndex)
            {
                case 0:
                    this.ApplicationBar = GenerateAppBar0();
                    break;
                case 1:
                    this.ApplicationBar = GenerateAppBarFuel();
                    ReadFuelData();
                    break;
                case 2:
                    this.ApplicationBar = GenerateAppBarMaintenance();
                    ReadMaintenanceData();
                    break;
                case 3:
                    this.ApplicationBar = GenerateAppBarGeneric();
                    ReadGenericData();
                    break;
            }
        }

        /// <summary>
        /// generate the application Bar for Vehicle details
        /// </summary>
        /// <returns>App bar with edit/delete </returns>
        private ApplicationBar GenerateAppBar0()
        {
            ApplicationBar appBar0 = new ApplicationBar();
            appBar0.Mode = ApplicationBarMode.Default;
            appBar0.Opacity = 1.0;
            appBar0.IsVisible = true;
            appBar0.IsMenuEnabled = false;

            //appBar0 edit button
            ApplicationBarIconButton btn_edit = new ApplicationBarIconButton();
            btn_edit.IconUri = new Uri("/Img/appbar_edit.png", UriKind.Relative);
            btn_edit.Text = AngeronaLang.edit;
            appBar0.Buttons.Add(btn_edit);
            btn_edit.Click += new EventHandler(btn_edit_Click);

            //help button
            ApplicationBarIconButton btn_help_details = new ApplicationBarIconButton();
            btn_help_details.IconUri = new Uri("/Img/appbar_help.png", UriKind.Relative);
            btn_help_details.Text = AngeronaLang.help;
            appBar0.Buttons.Add(btn_help_details);
            btn_help_details.Click += new EventHandler(btn_help_details_Click);

            ApplicationBarIconButton btn_delete = new ApplicationBarIconButton();
            btn_delete.IconUri = new Uri("/Img/appbar_delete.png", UriKind.Relative);
            btn_delete.Text = AngeronaLang.del;
            appBar0.Buttons.Add(btn_delete);
            btn_delete.Click += new EventHandler(btn_del_Click);

            return appBar0;
        }

        /// <summary>
        /// generate the Application Bar for Vehicle Fuel details
        /// </summary>
        /// <returns>App bar with add </returns>
        private ApplicationBar GenerateAppBarFuel()
        {
            //AppBar 1
            ApplicationBar appBar1 = new ApplicationBar();
            appBar1.Mode = ApplicationBarMode.Default;
            appBar1.Opacity = 1.0;
            appBar1.IsVisible = true;
            appBar1.IsMenuEnabled = false;

            ApplicationBarIconButton btn_add = new ApplicationBarIconButton();
            btn_add.IconUri = new Uri("/Img/appbar_add.png", UriKind.Relative);
            btn_add.Text = AngeronaLang.add;
            appBar1.Buttons.Add(btn_add);
            btn_add.Click += new EventHandler(btn_add_fuel_Click);

            //help button
            ApplicationBarIconButton btn_help_fuel = new ApplicationBarIconButton();
            btn_help_fuel.IconUri = new Uri("/Img/appbar_help.png", UriKind.Relative);
            btn_help_fuel.Text = AngeronaLang.help;
            appBar1.Buttons.Add(btn_help_fuel);
            btn_help_fuel.Click += new EventHandler(btn_help_fuel_Click);

            return appBar1;
        }

        /// <summary>
        /// generate the Application Bar for Vehicle Maintenance details
        /// </summary>
        /// <returns>App bar with add </returns>
        private ApplicationBar GenerateAppBarMaintenance()
        {
            //AppBar 1
            ApplicationBar appBar1 = new ApplicationBar();
            appBar1.Mode = ApplicationBarMode.Default;
            appBar1.Opacity = 1.0;
            appBar1.IsVisible = true;
            appBar1.IsMenuEnabled = false;

            ApplicationBarIconButton btn_add = new ApplicationBarIconButton();
            btn_add.IconUri = new Uri("/Img/appbar_add.png", UriKind.Relative);
            btn_add.Text = AngeronaLang.add;
            appBar1.Buttons.Add(btn_add);
            btn_add.Click += new EventHandler(btn_add_maintenance_Click);

            //help button
            ApplicationBarIconButton btn_help_mantinace = new ApplicationBarIconButton();
            btn_help_mantinace.IconUri = new Uri("/Img/appbar_help.png", UriKind.Relative);
            btn_help_mantinace.Text = AngeronaLang.help;
            appBar1.Buttons.Add(btn_help_mantinace);
            btn_help_mantinace.Click += new EventHandler(btn_help_mantinace_Click);

            return appBar1;
        }

        /// <summary>
        /// generate the Application Bar for Vehicle Generic details
        /// </summary>
        /// <returns>App bar with add </returns>
        private ApplicationBar GenerateAppBarGeneric()
        {
            //AppBar 3
            ApplicationBar appBar1 = new ApplicationBar();
            appBar1.Mode = ApplicationBarMode.Default;
            appBar1.Opacity = 1.0;
            appBar1.IsVisible = true;
            appBar1.IsMenuEnabled = false;

            ApplicationBarIconButton btn_add = new ApplicationBarIconButton();
            btn_add.IconUri = new Uri("/Img/appbar_add.png", UriKind.Relative);
            btn_add.Text = AngeronaLang.add;
            appBar1.Buttons.Add(btn_add);
            btn_add.Click += new EventHandler(btn_add_generic_Click);

            //help button
            ApplicationBarIconButton btn_help_generic = new ApplicationBarIconButton();
            btn_help_generic.IconUri = new Uri("/Img/appbar_help.png", UriKind.Relative);
            btn_help_generic.Text = AngeronaLang.help;
            appBar1.Buttons.Add(btn_help_generic);
            btn_help_generic.Click += new EventHandler(btn_help_generic_Click);

            return appBar1;
        }

        /// <summary>
        /// Handler of the click "Add Fuel". Opens the page /Views/AddFuel.xaml, sending the id taken from isolatedStorageSettings.ApplicationSettins["AutoCliccked"] as string.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_fuel_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(
                new Uri("/Views/AddFuel.xaml?" + 
                    "ID=" + IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string, 
                    UriKind.Relative));
        }

        /// <summary>
        /// Handler of the click "Add Generic". Opens the page /Views/AddGeneric.xaml, sending the id taken from isolatedStorageSettings.ApplicationSettins["AutoCliccked"] as string.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_generic_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(
                new Uri("/Views/AddGeneric.xaml?" +
                    "ID=" + IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string,
                    UriKind.Relative));
        }
        /// <summary>
        /// Handler of the click "Add Maintenance". Opens the page /Views/AddMaintenance.xaml, sending the id taken from isolatedStorageSettings.ApplicationSettins["AutoCliccked"] as string.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_add_maintenance_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(
                new Uri("/Views/AddMaintenance.xaml?" +
                    "ID=" + IsolatedStorageSettings.ApplicationSettings["AutoCliccked"] as string,
                    UriKind.Relative));
        }

        /// <summary>
        /// Handler of Edit button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_edit_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/ModCar.xaml", UriKind.Relative));
        }

        /// <summary>
        /// Handler of delete car button. 
        /// Shows a popup containing a messagebox that asks for confirm.
        /// Than deletes the reminder associated with the car and calls App.ViewModel.DeleteItem(Vehicle).
        /// It finally returns to NavigationService.GoBack();
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_del_Click(object sender, EventArgs e)
        {

            //Show messageBox for confirmation of deleting user data
            if (MessageBox.Show(AngeronaLang.areusure_deleteCar, AngeronaLang.delvehicle, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                if (IsolatedStorageSettings.ApplicationSettings.Contains("AutoCliccked"))
                {

                    ScheduledAction OldReminder = ScheduledActionService.Find("AssuranceDate" + Vehicle.VehicleName);
                    if (OldReminder != null)
                        ScheduledActionService.Remove(OldReminder.Name);

                    ScheduledAction OldReminder2 = ScheduledActionService.Find("Bollo" + Vehicle.VehicleName);
                    if (OldReminder2 != null)
                        ScheduledActionService.Remove(OldReminder2.Name);

                    ScheduledAction OldReminder3 = ScheduledActionService.Find("Revision" + Vehicle.VehicleName);
                    if (OldReminder3 != null)
                        ScheduledActionService.Remove(OldReminder3.Name);

                    // Deleting car image from isostore
                    if (Vehicle.ImageOfCar != null)
                    {
                        using (IsolatedStorageFile myIsoStoreFile = IsolatedStorageFile.GetUserStoreForApplication())
                        {
                            myIsoStoreFile.DeleteFile(Vehicle.ImageOfCar);
                        }
                    }

                    App.ViewModel.DeleteItem(Vehicle);
                    NavigationService.GoBack();
                }
            }
        }

        /// <summary>
        /// On Navigated Override. 
        /// When the user is taken to this page, the app RefreshAllData() for displaying freh data.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                RefreshAllData();
            }
        }

        /// <summary>
        /// Shows a MessageBox asking a confirmation. If accepted, deletes the element selected of the list.
        /// Than RefreshAllData() for displaying fresh data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Tap_Fuel(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if ((MessageBox.Show(AngeronaLang.areusure, AngeronaLang.deloperation, MessageBoxButton.OKCancel)) == MessageBoxResult.OK)
            {
                FuelData selectedElement = (FuelData)FuelList.SelectedItem;
                App.ViewModel.DeleteRefill(selectedElement);
                RefreshAllData();
            }
        }

        /// <summary>
        /// Shows a MessageBox asking a confirmation. If accepted, deletes the element selected of the list.
        /// Than RefreshAllData() for displaying fresh data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Tap_Generic(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if ((MessageBox.Show(AngeronaLang.areusure, AngeronaLang.deloperation, MessageBoxButton.OKCancel)) == MessageBoxResult.OK)
            {
                GenericData selectedElement = (GenericData)GenericList.SelectedItem;
                App.ViewModel.DeleteGeneric(selectedElement);
                RefreshAllData();
            }
        }

        /// <summary>
        /// Shows a MessageBox asking a confirmation. If accepted, deletes the element selected of the list.
        /// Than RefreshAllData() for displaying fresh data.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Tap_Maintenance(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if ((MessageBox.Show(AngeronaLang.areusure, AngeronaLang.deloperation, MessageBoxButton.OKCancel)) == MessageBoxResult.OK)
            {
                MaintenanceData selectedElement = (MaintenanceData)MaintenanceList.SelectedItem;
                App.ViewModel.DeleteMaintenance(selectedElement);
                RefreshAllData();
            }
        }

        //
        // Methods for showing Notes Of list selected.
        //
        private void tapOnElementFuelList(object sender, System.Windows.Input.GestureEventArgs e)
        {
            FuelData selectedElement = (FuelData)FuelList.SelectedItem;
            if(selectedElement.OperationNote != "")
                MessageBox.Show(selectedElement.OperationNote, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
            else
                MessageBox.Show(AngeronaLang.notentered, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
        }

        private void tapOnElementMaintenanceList(object sender, System.Windows.Input.GestureEventArgs e)
        {
            MaintenanceData selectedElement = (MaintenanceData)MaintenanceList.SelectedItem;
            if (selectedElement.OperationNote != "")
                MessageBox.Show(selectedElement.OperationNote, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
            else
                MessageBox.Show(AngeronaLang.notentered, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
        }

        private void tapOnElementGenericList(object sender, System.Windows.Input.GestureEventArgs e)
        {
            GenericData selectedElement = (GenericData)GenericList.SelectedItem;
            if (selectedElement.OperationNote != "")
                MessageBox.Show(selectedElement.OperationNote, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
            else
                MessageBox.Show(AngeronaLang.notentered, AngeronaLang.addanypagenote + ":", MessageBoxButton.OK);
        }

        private DateTime CheckAgeOrDefault(DateTime x)
        {
            DateTime temp = new DateTime(1754, 1, 1);
            if (x < temp)
            {
                MessageBox.Show(AngeronaLang.ReminderToOldDate, AngeronaLang.Error, MessageBoxButton.OK);
                x = defaultDate;
            }
            return x;
        }

        private void dp_fuel_date_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            dp_fuel_changed = true;
        }

        private void dp_man_date_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            dp_mantinace_changed = true;
        }

        private void dp_gen_date_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            dp_general_changed = true;
        }

        private void btn_help_details_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AngeronaLang.help_details, AngeronaLang.help, MessageBoxButton.OK);
        }

        private void btn_help_fuel_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AngeronaLang.help_fuel, AngeronaLang.help, MessageBoxButton.OK);
        }
        private void btn_help_mantinace_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AngeronaLang.help_mantinace, AngeronaLang.help, MessageBoxButton.OK);
        }
        private void btn_help_generic_Click(object sender, EventArgs e)
        {
            MessageBox.Show(AngeronaLang.help_generic, AngeronaLang.help, MessageBoxButton.OK);
        }
    }
}